package mask

import (
	"fmt"
	"regexp"
	"strings"
)

// 脱敏规范
var desMap = map[int][]int{
	2:  {1, 0},
	3:  {1, 0},
	4:  {2, 0},
	5:  {2, 0},
	6:  {2, 1},
	7:  {2, 2},
	8:  {2, 2},
	9:  {2, 3},
	10: {3, 3},
	11: {3, 4},
}

// Json json value脱敏
// keys 是key名，可指定多个， 处理时会忽略层级关系 所有同名key的value都会被处理
func Json(jstr string, keys ...string) string {
	for _, key := range keys {
		exp := regexp.MustCompile(`\"` + key + `\"\s*:\s*\"(.*?)\"`)
		matchArray := exp.FindAllStringSubmatch(jstr, -1)
		for _, match := range matchArray {
			if len(match) != 2 && match[1] == "" {
				continue
			}
			jstr = strings.ReplaceAll(jstr, match[1], String(match[1]))
		}
	}
	return jstr
}

// String 根据desMap 脱敏
func String(value string) string {
	if value == "" {
		return value
	}
	// 如果是邮箱，仅脱敏@以前的数据
	endFix := ""
	if strings.Contains(value, "@") {
		emailArray := strings.Split(value, "@")
		endFix = "@" + emailArray[1]
		value = emailArray[0]
	}
	desVal := ""
	valueLen := len(value)
	desSet, ok := desMap[valueLen]
	if !ok {
		desSet = []int{3, 4}
	}
	desStr := strings.Repeat("*", valueLen-desSet[0]-desSet[1])
	desVal = fmt.Sprintf("%s%s%s", value[:desSet[0]], desStr, value[valueLen-desSet[1]:valueLen])

	return fmt.Sprintf("%s%s", desVal, endFix)
}
